<?php

class Dispatcher
{
	private static $Instance;
	
	public static function GetInstance()
	{
		if (!isset(self::$Instance))
		{
			self::$Instance = new self;
		}
			
		return self::$Instance;
	}
	
	public function __construct()
	{
		if (!array_key_exists('/', Urls::GetPatterns()))
		{
			die('Please define a default route pattern.');
		}
	}
	
	public function Dispatch()
	{
		$Url = (empty($_GET['url']) ? '/' : '/' . rtrim($_GET['url'], '/'));
		$Route = Urls::Find($Url);
		
		$ControllerFile = 'application/controllers/' . strtolower($Route['Controller']) . '.php';
		$ControllerName = ucfirst($Route['Controller']) . 'Controller';
		$ControllerMethod = ucfirst($Route['Method']);
		$ControllerArguments = (!isset($Route['Arguments']) ? array() : $Route['Arguments']);
		
		if (!file_exists($ControllerFile))
		{
			die("The controller file '{$ControllerFile}' doesnt exist.");
		}
		
		require('application/controllers/appcontroller.php');
		require($ControllerFile);
		
		if (!class_exists($ControllerName))
		{
			die("The controller class '{$ControllerName}' doesnt exist.");
		}
		
		$Controller = new $ControllerName($Route['Controller'], $Route['Method']);
		$Controller->Initialize();
		
		if (!method_exists($Controller, $ControllerMethod))
		{
			die("The method '{$ControllerMethod}' doesnt exists.");
		}
		
		call_user_func_array(array($Controller, $ControllerMethod), $ControllerArguments);
	}
}